package com.quasar.hpatient.view.personal.setup;

import android.content.Intent;
import android.os.CountDownTimer;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.event.CloseEvent;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.medicalmodel.PatientInfoData;
import com.quasar.hpatient.onInterface.AnotherResultListener;
import com.quasar.hpatient.presenter.UpdatePhonePresenter;
import com.quasar.hpatient.utils.StringUtils;
import com.quasar.hpatient.view.LoginActivity_;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;

import java.util.Map;

import chatui.DemoHelper;
import cn.bmob.sms.BmobSMS;
import cn.bmob.sms.exception.BmobException;
import cn.bmob.sms.listener.RequestSMSCodeListener;
import cn.bmob.sms.listener.VerifySMSCodeListener;

/**
 * author : 许建宏
 * Date: 2017/10/9
 * View:修改手机号码
 */
@EActivity(R.layout.activity_update_phone)
public class UpdatePhoneActivity extends BaseActivity implements AnotherResultListener<DataStateResult> {

    String oldPwd = MainAppliaction.getInstance().getPWd();
    int count = 60;
    private UpdatePhonePresenter updatePhonePresenter;

    //密码
    @ViewById(R.id.et_password)
    EditText et_password;
    //新手机号码
    @ViewById(R.id.et_phone)
    EditText et_phone;
    //短信验证码
    @ViewById(R.id.et_verification)
    EditText et_verification;
    @ViewById(R.id.tv_verification)
    TextView tv_verification;

    @AfterViews
    void init() {

        ViseLog.d("enter");
        initView();
        initData();
    }

    @Override
    protected void initView() {
        initToolbar();
    }

    @Override
    protected void initData() {
        updatePhonePresenter = new UpdatePhonePresenter(this);
    }

    //提交
    @Click(R.id.bt_login)
    public void bt_login() {

        String pwd = et_password.getText().toString().trim();
        String phone = et_phone.getText().toString().trim();
        String yanZh = et_verification.getText().toString().trim();

        if (pwd.length() == 0) {
            et_password.setError("密码不能为空");
            et_password.requestFocus();
            return;
        }

        if (!pwd.equals(oldPwd)) {
            et_password.setError("密码输入错误");
            et_password.requestFocus();
            return;
        }

        if (phone.length() == 0) {
            et_phone.setError("手机号码不能为空");
            et_phone.requestFocus();
            return;
        }

        if (!phone.matches(StringUtils.isPhone)) {
            et_phone.setError("手机号码格式不正确");
            et_phone.requestFocus();
            return;
        }

        if (yanZh.length() == 0) {
            et_verification.setError("验证码不能为空");
            et_verification.requestFocus();
            return;
        }

        VerificationSms(phone);
    }

    //获取验证码
    @Click(R.id.tv_verification)
    public void tv_verification() {

        String phone = et_phone.getText().toString().trim();
        if (!phone.matches(StringUtils.isPhone)) {
            et_phone.setError("手机号码不合法");
            et_phone.requestFocus();
            return;
        }

        if (phone.length() != 11) {
            et_phone.requestFocus();
            et_phone.setError("请输入手机号");
            return;
        }

        BmobSMS.requestSMSCode(this, phone, ConstantManger.SMS, new RequestSMSCodeListener() {
            @Override
            public void done(Integer integer, BmobException e) {
                if (e == null) {
                    msg("短信已发送");
                    tv_verification.setEnabled(false);   //不可点击
                    countDownTimer(); //倒计时
                }
            }
        });
    }

    /**
     * 短信倒计时
     */
    private void countDownTimer() {
        new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                if (count != 0) {
                    count--;
                    tv_verification.setText(count + "s");
                }
            }

            //倒计时完成
            @Override
            public void onFinish() {
                count = 60;
                tv_verification.setText(count + "s");
                tv_verification.setEnabled(true);// 可点击
                tv_verification.setText("获取验证码");
            }
        }.start();
    }

    /**
     * 验证短信是都成功
     *
     * @param phoneNumber 新手机号码
     */
    public void VerificationSms(final String phoneNumber) {
        ViseLog.d("enter");
        final String phone = et_phone.getText().toString().trim();
        BmobSMS.verifySmsCode(this, phone, et_verification.getText().toString().trim(),
                new VerifySMSCodeListener() {

                    @Override
                    public void done(BmobException ex) {
                        // TODO Auto-generated method stub
                        if (ex == null) {// 短信验证码已验证成功
                            ViseLog.d("bmob", "验证通过");
                            updatePhonePresenter.UpdatePhoneOperation(phoneNumber);
                        } else {
                            ViseLog.d("bmob", "验证失败：code =" + ex.getErrorCode()
                                    + ",msg = " + ex.getLocalizedMessage());
                            msg("验证码失败");
                        }
                    }
                });
    }

    @Override
    public void onSuccess(DataStateResult data) {
        if(data.getMsgCode().equals("0x00000000")){
            msg("用户修改手机号码成功");
            String phone = et_phone.getText().toString().trim();
            //保存账号
            MainAppliaction.getInstance().setUserName(phone);
            chatUi();
        }

    }

    @Override
    public void onError(String msg) {
        ViseLog.d("onError" + msg);
        if (msg != null) {
            msg(msg);
        }
    }

    @Override
    public void onRefreshUI() {
        ViseLog.d("onComplete");
    }


    //退出环信
    public void chatUi() {
        DemoHelper.getInstance().logout(false, new EMCallBack() {
            @Override
            public void onSuccess() {
                EventBus.getDefault().post(new CloseEvent());
                LoginActivity_.intent(UpdatePhoneActivity.this).start();
                finish();
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {

            }
        });
    }
}
